package sanphone.com.runningschool.LogIn;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import sanphone.com.runningschool.BaseActivity;
import sanphone.com.runningschool.ForceOffline;
import sanphone.com.runningschool.InterfaceLocation;
import sanphone.com.runningschool.MainActivity;
import sanphone.com.runningschool.PersonalInfo.PersonalInfoEditActivity;
import sanphone.com.runningschool.R;
import sanphone.com.runningschool.RequestHttp.RequestHttp;
import sanphone.com.runningschool.entity.User;

public class LogInActivity extends BaseActivity {
    SharedPreferences sprfLogIn;
    SharedPreferences.Editor editorMain, editorLogIn;
    private Button loginButton;
    private EditText idText, passwordText;
    private String idStr, passwordStr;


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局文件前判断是否登陆过
        sprfLogIn = PreferenceManager.getDefaultSharedPreferences(this);
        editorLogIn = sprfLogIn.edit();
        if (sprfLogIn.getBoolean("main", false)) {
            startActivity(new Intent(LogInActivity.this, MainActivity.class));
            LogInActivity.this.finish();
        }

        setContentView(R.layout.activity_log_in);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("登录");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            //actionBar.setHomeAsUpIndicator();
        }

        initView();

    }

    private void initView() {
        idText = findViewById(R.id.user_account);
        passwordText = findViewById(R.id.user_password);
        loginButton = findViewById(R.id.user_login);
//        ForceOffline offline=new ForceOffline(idText.getText().toString());
//        if(offline.check()==false){
//            sendBroadcast(new Intent("Intent.FORCE_OFFLINE"));
//        }
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                idStr = idText.getText().toString();
                passwordStr = passwordText.getText().toString();
                //线程池
                final ExecutorService executor = Executors.newSingleThreadExecutor();
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject json = new JSONObject();
                        try {
                            json.put("schoolId", idStr);
                            json.put("password", passwordStr);
                            RequestHttp requestHttp = new RequestHttp(InterfaceLocation.getLocation() + "login",LogInActivity.this);
                            String request = requestHttp.login(json);
                            JSONObject requestJson = new JSONObject(request);
                            if (requestJson.getString("data").equals("登录失败")) {
                                //Log.e("test", requestJson.getString("data") );
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(LogInActivity.this, "账号或者密码错误！", Toast.LENGTH_SHORT).show();

                                    }
                                });
                            } else {
                                String result = requestJson.getString("data");
                                Gson gson = new Gson();
                                final User user = gson.fromJson(result, User.class);
                                // TODO: 2018/7/26 当资料为空时，提示用户跳到资料编辑页面完善资料
                                if (user.getNickName() == null) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            AlertDialog.Builder alter = new AlertDialog.Builder(LogInActivity.this);
                                            alter.setTitle("温馨提示").setMessage("请前去完善个人资料").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    editorMain = getSharedPreferences("data", MODE_PRIVATE).edit();
                                                    editorMain.putString("schoolId", user.getSchoolId());
                                                    editorMain.putString("token",user.getToken());
                                                    editorMain.apply();
                                                    editorLogIn= PreferenceManager.getDefaultSharedPreferences(LogInActivity.this).edit();
                                                    editorLogIn.putBoolean("main", true);
                                                    editorLogIn.commit();
                                                    Intent intent = new Intent(LogInActivity.this, PersonalInfoEditActivity.class);
                                                    startActivity(intent);
                                                    LogInActivity.this.finish();
                                                }
                                            });
                                            alter.create();
                                            alter.show();
                                        }
                                    });

                                } else {
                                    ForceOffline offline = new ForceOffline(user.getSchoolId(), LogInActivity.this);
                                    offline.check();
                                    Intent intent2 = new Intent(LogInActivity.this, MainActivity.class);
                                   editorLogIn= PreferenceManager.getDefaultSharedPreferences(LogInActivity.this).edit();
                                    editorLogIn.putBoolean("main", true);
                                    editorLogIn.commit();
                                    editorMain = getSharedPreferences("data", MODE_PRIVATE).edit();
                                    editorMain.putString("schoolId", user.getSchoolId());
                                    editorMain.putString("userName", user.getRealName());
                                    editorMain.putString("userPhone", user.getPhone());
                                    editorMain.putString("nickName", user.getNickName());
                                    editorMain.putString("dormitory", user.getDormitory());
                                    editorMain.putString("token",user.getToken());
                                    editorMain.apply();
                                    intent2.putExtra("id", user.getSchoolId());
                                    startActivity(intent2);
                                    LogInActivity.this.finish();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LogInActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();

                                        }
                                    });

                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                executor.shutdown();
            }
        });
    }
}
